from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from QQLoginTool.QQtool import OAuthQQ

from oauth.utils import generic_access_token

"""
用户点击qq登录按钮的时候,前端发送一个ajax请求,后端将生成的url返回给前端

GET   /oauth/qq/statues/?state=xxx
"""
from django.conf import settings

# from mall import settings

class OauthQQURLView(APIView):

    """

    生成url
    """
    def get(self,request):

        state = '/'

        #1.创建对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=state)
        #2.调用对象的方法,获取url

        url = oauth.get_qq_url()

        # url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101474184&redirect_uri=http://www.meiduo.site:8080/oauth_callback.html&state=test"

        return Response({'login_url':url})

"""
当用户扫描成功之后,腾讯服务器会生成一个code,我们前端需要将code返回给后端

接收code,通过code换取token

GET    /oauth/qq/users/?code=xxx

"""
from rest_framework import status
from .models import OAuthQQUser
from .serializers import OauthQQUserSerializer

class OauthQQUserView(APIView):

    def get(self,request):
        # 1接收code,
        code = request.query_params.get('code')

        if code is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 2通过code换取token
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI
                        )
        access_token = oauth.get_access_token(code)

        openid = oauth.get_open_id(access_token)

        #获取到openid之后,我们要查询一下数据库,是否含有这个openid
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 如果没有,就说明用户没有绑定过

            """
            1.openid是比较敏感的数据,我们最好对这个数据进行加密
            2.我们这个数据最好设置一个有效期
            """
            #要将openid进行加密处理
            access_token = generic_access_token(openid)

            return Response({'access_token':access_token})
        else:
            #如果有,就说明用户绑定过,就应该跳转到首页去
            #登录成功了我们应该返回token

            from rest_framework_jwt.settings import api_settings
            # 1.我们需要获取rest_framework_jwt的两个方法
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            # 2.将用户信息给payload,然后进行编码
            payload = jwt_payload_handler(qquser.user)
            token = jwt_encode_handler(payload)

            return Response({
                'token':token,
                'username':qquser.user.username,
                'user_id':qquser.user.id
            })

    """
    当用户输入完绑定信息之后,前端应将 手机号,密码,短信验证码,openid(处理过的)传递给后端
    1.接收数据
    2.校验数据
        2.1短信验证码
        2.2openid(处理过的)
        2.3根据手机号查询用户信息,判断用户是否存在
    3.保存数据
    4.返回响应

    POST
    """

    def post(self,request):
        # 1.接收数据
        data = request.data
        # 2.校验数据 --->序列化器
        serializer = OauthQQUserSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        # 3.保存数据
        qquser = serializer.save()
        # 4.返回响应
        from rest_framework_jwt.settings import api_settings
        # 1.我们需要获取rest_framework_jwt的两个方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        # 2.将用户信息给payload,然后进行编码
        payload = jwt_payload_handler(qquser.user)
        token = jwt_encode_handler(payload)

        return Response({
            'token': token,
            'username': qquser.user.username,
            'user_id': qquser.user.id
        })







# from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
# from django.conf import settings
# #1.创建序列化器
# #secret_key     秘钥,我们一般使用的是settings文件中的secret_key
# #expires_in = None   过期时间,单位是秒数
# serializer = Serializer(settings.SECRET_KEY,3600)
#
# #2.组织数据
# data = {'openid':'12345678'}
#
# #3.对数据进行加密
# token = serializer.dumps(data)
#
# #解密
# serializer.loads(token)
#
# #有效期
# serializer = Serializer(settings.SECRET_KEY,1)
#
# #2.组织数据
# data = {'openid':'12345678'}
#
# #加密
# token = serializer.dumps(data)
#
# #解密
# serializer.loads(token)



